Making Maps Programming

Basic libraries to start:

#install.packages(c("cowplot", "googleway", "ggplot2", "ggrepel", 
#"ggspatial", "libwgeom", "sf", "rnaturalearth", "rnaturalearthdata"))

Preparing information:

library("ggplot2")
theme_set(theme_bw()) #best for maps
library("sf")
## Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library("plotly")
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library("rnaturalearth")  #country world maps
library("rnaturalearthdata") # necesarie to scale = "large" 

mundo <- ne_countries(scale = "medium", returnclass = "sf")
# Check some structure
class(mundo)
## [1] "sf"         "data.frame"
str(mundo)
## Classes 'sf' and 'data.frame':   241 obs. of  64 variables:
##  $ scalerank : int  3 1 1 1 1 3 3 1 1 1 ...
##  $ featurecla: chr  "Admin-0 country" "Admin-0 country" "Admin-0 country" "Admin-0 country" ...
##  $ labelrank : num  5 3 3 6 6 6 6 4 2 6 ...
##  $ sovereignt: chr  "Netherlands" "Afghanistan" "Angola" "United Kingdom" ...
##  $ sov_a3    : chr  "NL1" "AFG" "AGO" "GB1" ...
##  $ adm0_dif  : num  1 0 0 1 0 1 0 0 0 0 ...
##  $ level     : num  2 2 2 2 2 2 2 2 2 2 ...
##  $ type      : chr  "Country" "Sovereign country" "Sovereign country" "Dependency" ...
##  $ admin     : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ adm0_a3   : chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ geou_dif  : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ geounit   : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ gu_a3     : chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ su_dif    : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ subunit   : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ su_a3     : chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ brk_diff  : num  0 0 0 0 0 0 0 0 0 0 ...
##  $ name      : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ name_long : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ brk_a3    : chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ brk_name  : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ brk_group : chr  NA NA NA NA ...
##  $ abbrev    : chr  "Aruba" "Afg." "Ang." "Ang." ...
##  $ postal    : chr  "AW" "AF" "AO" "AI" ...
##  $ formal_en : chr  "Aruba" "Islamic State of Afghanistan" "People's Republic of Angola" NA ...
##  $ formal_fr : chr  NA NA NA NA ...
##  $ note_adm0 : chr  "Neth." NA NA "U.K." ...
##  $ note_brk  : chr  NA NA NA NA ...
##  $ name_sort : chr  "Aruba" "Afghanistan" "Angola" "Anguilla" ...
##  $ name_alt  : chr  NA NA NA NA ...
##  $ mapcolor7 : num  4 5 3 6 1 4 1 2 3 3 ...
##  $ mapcolor8 : num  2 6 2 6 4 1 4 1 1 1 ...
##  $ mapcolor9 : num  2 8 6 6 1 4 1 3 3 2 ...
##  $ mapcolor13: num  9 7 1 3 6 6 8 3 13 10 ...
##  $ pop_est   : num  103065 28400000 12799293 14436 3639453 ...
##  $ gdp_md_est: num  2258 22270 110300 109 21810 ...
##  $ pop_year  : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ lastcensus: num  2010 1979 1970 NA 2001 ...
##  $ gdp_year  : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ economy   : chr  "6. Developing region" "7. Least developed region" "7. Least developed region" "6. Developing region" ...
##  $ income_grp: chr  "2. High income: nonOECD" "5. Low income" "3. Upper middle income" "3. Upper middle income" ...
##  $ wikipedia : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ fips_10   : chr  NA NA NA NA ...
##  $ iso_a2    : chr  "AW" "AF" "AO" "AI" ...
##  $ iso_a3    : chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ iso_n3    : chr  "533" "004" "024" "660" ...
##  $ un_a3     : chr  "533" "004" "024" "660" ...
##  $ wb_a2     : chr  "AW" "AF" "AO" NA ...
##  $ wb_a3     : chr  "ABW" "AFG" "AGO" NA ...
##  $ woe_id    : num  NA NA NA NA NA NA NA NA NA NA ...
##  $ adm0_a3_is: chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ adm0_a3_us: chr  "ABW" "AFG" "AGO" "AIA" ...
##  $ adm0_a3_un: num  NA NA NA NA NA NA NA NA NA NA ...
##  $ adm0_a3_wb: num  NA NA NA NA NA NA NA NA NA NA ...
##  $ continent : chr  "North America" "Asia" "Africa" "North America" ...
##  $ region_un : chr  "Americas" "Asia" "Africa" "Americas" ...
##  $ subregion : chr  "Caribbean" "Southern Asia" "Middle Africa" "Caribbean" ...
##  $ region_wb : chr  "Latin America & Caribbean" "South Asia" "Sub-Saharan Africa" "Latin America & Caribbean" ...
##  $ name_len  : num  5 11 6 8 7 5 7 20 9 7 ...
##  $ long_len  : num  5 11 6 8 7 13 7 20 9 7 ...
##  $ abbrev_len: num  5 4 4 4 4 5 4 6 4 4 ...
##  $ tiny      : num  4 NA NA NA NA 5 5 NA NA NA ...
##  $ homepart  : num  NA 1 1 NA 1 NA 1 1 1 1 ...
##  $ geometry  :sfc_MULTIPOLYGON of length 241; first list element: List of 1
##   ..$ :List of 1
##   .. ..$ : num [1:10, 1:2] -69.9 -69.9 -69.9 -70 -70.1 ...
##   ..- attr(*, "class")= chr [1:3] "XY" "MULTIPOLYGON" "sfg"
##  - attr(*, "sf_column")= chr "geometry"
##  - attr(*, "agr")= Factor w/ 3 levels "constant","aggregate",..: NA NA NA NA NA NA NA NA NA NA ...
##   ..- attr(*, "names")= chr [1:63] "scalerank" "featurecla" "labelrank" "sovereignt" ...
colnames(mundo)
##  [1] "scalerank"  "featurecla" "labelrank"  "sovereignt" "sov_a3"    
##  [6] "adm0_dif"   "level"      "type"       "admin"      "adm0_a3"   
## [11] "geou_dif"   "geounit"    "gu_a3"      "su_dif"     "subunit"   
## [16] "su_a3"      "brk_diff"   "name"       "name_long"  "brk_a3"    
## [21] "brk_name"   "brk_group"  "abbrev"     "postal"     "formal_en" 
## [26] "formal_fr"  "note_adm0"  "note_brk"   "name_sort"  "name_alt"  
## [31] "mapcolor7"  "mapcolor8"  "mapcolor9"  "mapcolor13" "pop_est"   
## [36] "gdp_md_est" "pop_year"   "lastcensus" "gdp_year"   "economy"   
## [41] "income_grp" "wikipedia"  "fips_10"    "iso_a2"     "iso_a3"    
## [46] "iso_n3"     "un_a3"      "wb_a2"      "wb_a3"      "woe_id"    
## [51] "adm0_a3_is" "adm0_a3_us" "adm0_a3_un" "adm0_a3_wb" "continent" 
## [56] "region_un"  "subregion"  "region_wb"  "name_len"   "long_len"  
## [61] "abbrev_len" "tiny"       "homepart"   "geometry"
head(mundo, 6)
tail(mundo, 6)

Data and Basic Plots (coord_sf y geom_sf)

ggplot(data = mundo)+
  geom_sf()

Title, subtitle and axes labels (ggtitle, xlab, ylab)

ggplot(data = mundo)+
  geom_sf()+
  xlab("Longitud")+ylab("Latitude")+
  ggtitle("World Maps", subtitle = paste0("(",length(unique(mundo$name)), "country)"))

Color Map (geom_sf)

A first simple map:

ggplot(data = mundo)+
  geom_sf(color = "black", fill = "blue")

Generating a best map:

a <- ggplot(data = mundo) +
    geom_sf(aes(fill = pop_est)) +
    scale_fill_viridis_c(option = "plasma", trans = "sqrt")
a

Projection and Extension (coord_sf)

coord_sf allow work with coordenate system including both projections and extensions of map. The argument crs is possible overwrite the configuration and project wherever. This can be use with all kind of validation of PROJ4 string.

ggplot(data = mundo) +
    geom_sf() +
    coord_sf(crs = "+proj=laea +lat_0=52 +lon_0=10 +x_0=4321000 +y_0=3210000 +ellps=GRS80 +units=m +no_defs ")

If we want to use Spatial Reference System Identifier (SRID) or European Petroleum Survey Group (EPSG) code available for Peru:

ggplot(data = mundo) +
    geom_sf() +
    coord_sf(crs = "+init=epsg:3035")

ggplot(data = mundo) +
    geom_sf() +
    coord_sf(crs = st_crs(3035))

We generate zoom in Peru to add the map of South America. Let´s go (Vamos)!

ggplot(data = mundo) +
    geom_sf() +
    coord_sf(xlim = c(-90.00, -30.5), ylim = c(-57.00, 14.00), expand = FALSE)

Arrow and Scale (ggspatial)

Exist a variety of packages like prettymapr, vsd, ggsn, legendMap. We are going to use ggspatial.

library(ggspatial)
ggplot(data = mundo) +
    geom_sf() +
    annotation_scale(location = "bl", width_hint = 0.4) +
    annotation_north_arrow(location = "bl", which_north = "true", 
        pad_x = unit(2.70, "in"), pad_y = unit(3.80, "in"),
        style = north_arrow_fancy_orienteering) +
    coord_sf(xlim = c(-90.00, -30.5), ylim = c(-57.00, 14.00))

## Scale on map varies by more than 10%, scale bar may be inaccurate

Name of City and Others (geom_text, annotate)

We can use like we see at the beginning of the data world how to regularize a data.frame in ggplot2.

library("sf")
sf_use_s2(FALSE)
## Spherical geometry (s2) switched off
world_points<- st_centroid(mundo)
world_points <- cbind(mundo, st_coordinates(st_centroid(mundo$geometry)))

mundo <- mundo %>%
  dplyr::rename(Poblacion = pop_est) 

ggplot(data = mundo) +
geom_sf(aes(fill = Poblacion)) +
    scale_fill_viridis_c(option = "plasma", trans = "sqrt")+
geom_text(data= world_points[world_points$continent=="South America", ],aes(x=X, y=Y, label=name),
    color = "black", fontface = "bold", check_overlap = FALSE, size = 3) +
annotate(geom = "text", x = -80, y = -20, label = "O. Pacífico", 
    fontface = "italic", color = "grey22", size = 4) +
annotation_scale(location = "bl", width_hint = 0.4) +
    annotation_north_arrow(location = "bl", which_north = "true", 
        pad_x = unit(2.65, "in"), pad_y = unit(3.70, "in"),
        style = north_arrow_fancy_orienteering) +
    coord_sf(xlim = c(-90.00, -30.5), ylim = c(-57.00, 14.00))+
   xlab("Longitud") + ylab("Latitude") + 
  ggtitle("Mapa de Población de Sudamérica") + 
  theme(panel.grid.major = element_line(color = gray(.5), linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "aliceblue"))

Save Map

ggsave("map.pdf")
ggsave("map_web.png", width = 6, height = 6, dpi = "screen")

Adding Shape of Dots and Polygons:

Dot Data:

Creamos puntos de Data entre la Isla San Lorenzo y Lima:

(sites <- data.frame(longitude = c(-78, -77), latitude = c(-11, 
    -12.5)))
  • Plotemos esas coordenadas (forma rapida):
m <- ggplot(data = mundo) +
    geom_sf() +
    geom_point(data = sites, aes(x = longitude, y = latitude), size = 3, 
        shape = 23, fill = "darkred") +
    coord_sf(xlim = c(-79, -75), ylim = c(-10, -15), expand = FALSE)
ggplotly(m)
  • Forma adecuada:

Una alternativa mejor y más flexible es usar el poder de sf: convertir el marco de datos en un objeto sf permite confiar en sf para manejar sobre la marcha el sistema de coordenadas (proyección y extensión), lo cual puede ser muy útil si los dos los objetos (aquí mapa del mundo y sitios) no están en la misma proyección. Para lograr el mismo resultado, la proyección (aquí WGS84, que es el código CRS #4326) tiene que estar definida a priori en el objeto sf:

(sites <- st_as_sf(sites, coords = c("longitude", "latitude"), 
    crs = 4326, agr = "constant"))
ggplot(data = mundo) +
    geom_sf() +
    geom_sf(data = sites, size = 3, shape = 23, fill = "darkred") +
    coord_sf(xlim = c(-80, -74), ylim = c(-8, -14), expand = FALSE)

Poligonos de Data:

Departamento <- st_read(
  "data_peru/DEPARTAMENTOS.shp")
## Reading layer `DEPARTAMENTOS' from data source 
##   `D:\1.2Autonomo_AI\1er_entregable\ANS_Github\data_peru\DEPARTAMENTOS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 25 features and 4 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.32823 ymin: -18.35093 xmax: -68.65228 ymax: -0.03860597
## Geodetic CRS:  WGS 84
ggplot() + 
  geom_sf(data = Departamento, size = 3, color = "black", fill = "blue" ) + 
  ggtitle("Departamentos del Perú") + 
  coord_sf()

Provincias <- st_read("data_peru/PROVINCIAS.shp")
## Reading layer `PROVINCIAS' from data source 
##   `D:\1.2Autonomo_AI\1er_entregable\ANS_Github\data_peru\PROVINCIAS.shp' 
##   using driver `ESRI Shapefile'
## Simple feature collection with 196 features and 7 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -81.32823 ymin: -18.35093 xmax: -68.65228 ymax: -0.03860597
## Geodetic CRS:  WGS 84
Departamentos <- Provincias %>% group_by(DEPARTAMEN) %>%
  dplyr::summarise(
    tot_area = sum(Area),
    ID = unique(IDDPTO)
  )
head(Departamentos)
sf_use_s2(FALSE)
Departamentos <- cbind(Departamentos, st_coordinates(st_centroid(Departamentos)))
Provincias <- cbind(Provincias, st_coordinates(st_centroid(Provincias)))
library("tools")
Departamentos$DEPARTAMEN <- toTitleCase(Departamentos$DEPARTAMEN)
head(Departamentos)
t <- ggplot(data = mundo) +
  geom_sf(fill = "gray90") +
   geom_sf(data = sites, size = 5, shape = 23, fill = "darkred")+
  geom_sf(data = Departamentos, fill = Departamentos$tot_area) + 
    scale_fill_viridis_c(option = "plasma") +
    geom_text(data = Departamentos, aes(X, Y, label = DEPARTAMEN), size = 3) +
    annotation_scale(location = "bl", width_hint = 0.4) +
  annotation_north_arrow(location = "bl", which_north = "true", 
        pad_x = unit(0.50, "in"), pad_y = unit(0.40, "in"),
        style = north_arrow_nautical)+
    coord_sf(xlim = c(-80, -74), ylim = c(-10, -14), expand = FALSE)+
  xlab("Longitud") + ylab("Latitud") +
    ggtitle("Análisis Geoespacial", subtitle = "(Departamento Liima)") +
    theme(panel.grid.major = element_line(color = gray(0.5), linetype = "dashed", 
        size = 0.5), panel.background = element_rect(fill = "aliceblue"))
db_ciudades <- read.csv(file="data_peru/pe.csv", header =  TRUE)
cols <- c("Lima", "Cerro de Pasco", "Junin", "Huancavelica")
db_ciudad <- db_ciudades[db_ciudades$city %in% cols, ]

(flcities <- st_as_sf(db_ciudad, coords = c("lng", "lat"), remove = FALSE, 
    crs = 4326, agr = "constant"))

Agregamos labels:

library(ggrepel)
tt <- ggplot(data = mundo) +
  geom_sf(fill = "antiquewhite1") +
  geom_sf(data = Departamentos) + 
  geom_sf(data = Provincias[Provincias$DEPARTAMEN=="LIMA", ], 
          aes(fill = Provincias[Provincias$DEPARTAMEN=="LIMA", ]$Area))+
  guides(fill=guide_legend(title="Area(km^2)"))+
  scale_fill_viridis_c(option = "plasma")+
  geom_sf(data = sites, size = 5, shape = 23, fill = "darkred")+
     coord_sf(xlim = c(-80, -74), ylim = c(-10, -14), expand = FALSE)+
  geom_sf(data = flcities) +
  geom_text_repel(data = flcities, aes(x = lng, y = lat, label = city), 
        fontface = "bold", nudge_x = c(0.2, 0.5, 0.6, 0.6), nudge_y = c(0.25, 
            0.25, 0.25, -0.25)) +
  geom_label(data = Provincias[Provincias$DEPARTAMEN=="LIMA", ],
               aes(X, Y, label = CAPITAL), size = 2) +
  annotation_scale(location = "bl", width_hint = 0.4) +
  annotation_north_arrow(location = "bl", which_north = "true", 
        pad_x = unit(0.50, "in"), pad_y = unit(0.40, "in"),
        style = north_arrow_nautical)+
    coord_sf(xlim = c(-80, -74), ylim = c(-10, -14), expand = FALSE)+
   xlab("Longitud") + ylab("Latitud") +
    ggtitle("Análsis Geoespacial", subtitle = "(En provincia Lima)") +
    theme(panel.grid.major = element_line(color = gray(0.5), linetype = "dashed", 
        size = 0.5), panel.background = element_rect(fill = "aliceblue"))
tt

Multiples Mapas en R:

Conceptos Generales:

(g1  <- qplot(0:10, 0:10))

(g1_void <- g1 + theme_void() + theme(panel.border = element_rect(colour = "black", 
    fill = NA)))

g1 +
    annotation_custom(
        grob = ggplotGrob(g1_void),
        xmin = 0,
        xmax = 3,
        ymin = 5,
        ymax = 10
    ) +
    annotation_custom(
        grob = ggplotGrob(g1_void),
        xmin = 5,
        xmax = 10,
        ymin = 0,
        ymax = 3
    )

library(cowplot) 
ggdraw(g1) + draw_plot(g1_void, width = 0.25, height = 0.5, x = 0.02, y = 0.48) + draw_plot(g1_void, width = 0.5, height = 0.25, x = 0.75, y = 0.09)

(gworld <- ggplot(data = mundo) +
  geom_sf(aes(fill = region_wb)) +
  geom_rect(xmin = -102.15, xmax = -74.12, ymin = 7.65, ymax = 33.97, 
     fill = NA, colour = "black", size = 1.5) +
  scale_fill_viridis_d(option = "plasma") +
  theme(panel.background = element_rect(fill = "azure"),
     panel.border = element_rect(fill = NA)))

(ggulf <- ggplot(data = mundo) +
  geom_sf(aes(fill = region_wb)) +
  annotate(geom = "text", x = -90, y = 26, label = "Gulf of Mexico", 
     fontface = "italic", color = "grey22", size = 6) +
  coord_sf(xlim = c(-102.15, -74.12), ylim = c(7.65, 33.97), expand = FALSE) +
  scale_fill_viridis_d(option = "plasma") +
  theme(legend.position = "none", axis.title.x = element_blank(), 
     axis.title.y = element_blank(), panel.background = element_rect(fill = "azure"), 
     panel.border = element_rect(fill = NA)))

ggplot() +
    coord_equal(xlim = c(0, 3.3), ylim = c(0, 1), expand = FALSE) +
    annotation_custom(ggplotGrob(gworld), xmin = 0, xmax = 1.5, ymin = 0, 
                    ymax = 1) +
    annotation_custom(ggplotGrob(ggulf), xmin = 1.5, xmax = 3, ymin = 0, 
                    ymax = 1) +
    theme_void()

plot_grid(gworld, ggulf, nrow = 1, rel_widths = c(2.3, 1))

ggsave("grid.pdf", width = 15, height =  5)

Inserción de Mapas:

peru <- subset(mundo, admin =="Peru")
map_peru <- ggplot(data = peru)+
  geom_sf(fill="cornsilk")+
  coord_sf(crs = st_crs(5387))
tumbes <- ggplot(data = peru)+
  geom_sf(fill="cornsilk")+
coord_sf(xlim=c(-82, -80),ylim=c(-3,-5), datum = NA)

ggdraw(map_peru)+
  draw_plot(tumbes, width = 0.20, height = 0.20, x = 0.30, y = 0.20)

Dibujando una zona con mapas pequeños:

sites <- st_as_sf(data.frame(longitude = c(-80.15, -80.1), latitude = c(26.5, 
26.8)), coords = c("longitude", "latitude"), crs = 4326, 
agr = "constant")


(florida <- ggplot(data = mundo) +
     geom_sf(fill = "antiquewhite1") +
     geom_sf(data = sites, size = 4, shape = 23, fill = "darkred") +
     annotate(geom = "text", x = -85.5, y = 27.5, label = "Gulf of Mexico", 
         color = "grey22", size = 4.5) +
     coord_sf(xlim = c(-87.35, -79.5), ylim = c(24.1, 30.8)) +
     xlab("Longitude")+ ylab("Latitude")+
     theme(panel.grid.major = element_line(colour = gray(0.5), linetype = "dashed", 
         size = 0.5), panel.background = element_rect(fill = "aliceblue"), 
         panel.border = element_rect(fill = NA)))

(siteA <- ggplot(data = mundo) +
     geom_sf(fill = "antiquewhite1") +
     geom_sf(data = sites, size = 4, shape = 23, fill = "darkred") +
     coord_sf(xlim = c(-80.25, -79.95), ylim = c(26.65, 26.95), expand = FALSE) + 
     annotate("text", x = -80.18, y = 26.92, label= "Site A", size = 6) + 
     theme_void() + 
     theme(panel.grid.major = element_line(colour = gray(0.5), linetype = "dashed", 
         size = 0.5), panel.background = element_rect(fill = "aliceblue"), 
         panel.border = element_rect(fill = NA)))

(siteB <- ggplot(data = mundo) + 
     geom_sf(fill = "antiquewhite1") +
     geom_sf(data = sites, size = 4, shape = 23, fill = "darkred") +
     coord_sf(xlim = c(-80.3, -80), ylim = c(26.35, 26.65), expand = FALSE) +
     annotate("text", x = -80.23, y = 26.62, label= "Site B", size = 6) + 
     theme_void() +
     theme(panel.grid.major = element_line(colour = gray(0.5), linetype = "dashed", 
         size = 0.5), panel.background = element_rect(fill = "aliceblue"), 
         panel.border = element_rect(fill = NA)))

#Dos flechas:
arrowA <- data.frame(x1 = 18.5, x2 = 23, y1 = 9.5, y2 = 14.5)
arrowB <- data.frame(x1 = 18.5, x2 = 23, y1 = 8.5, y2 = 6.5)

Mapa Final:

# ggplot() +
#     coord_equal(xlim = c(0, 28), ylim = c(0, 20), expand = FALSE) +
#     annotation_custom(ggplotGrob(florida), xmin = 0, xmax = 20, ymin = 0, 
#         ymax = 20) +
#     annotation_custom(ggplotGrob(siteA), xmin = 20, xmax = 28, ymin = 11.25, 
#         ymax = 19) +
#     annotation_custom(ggplotGrob(siteB), xmin = 20, xmax = 28, ymin = 2.5, 
#         ymax = 10.25) +
#     geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = arrowA, 
#         arrow = arrow(), lineend = "round") +
#     geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = arrowB, 
#         arrow = arrow(), lineend = "round") +
#     theme_void()
#Tambien con draw_plot:
ggdraw(xlim = c(0, 28), ylim = c(0, 20)) +
    draw_plot(florida, x = 0, y = 0, width = 20, height = 20) +
    draw_plot(siteA, x = 20, y = 11.25, width = 8, height = 8) +
    draw_plot(siteB, x = 20, y = 2.5, width = 8, height = 8) +
    geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = arrowA, 
        arrow = arrow(), lineend = "round") +
    geom_segment(aes(x = x1, y = y1, xend = x2, yend = y2), data = arrowB, 
        arrow = arrow(), lineend = "round")

Guardando:

ggsave("florida-sites.pdf", width = 10, height = 7)

Generando Gráficos de Distribución y Boxplot de Areas:

Plot <- Provincias[Provincias$DEPARTAMEN=="LIMA", ]
histograma <- ggplot(data=Provincias)+
  geom_histogram(mapping = aes(x=Area))+
  ggtitle(label = "Histograma de Areas de Lima", subtitle = "A.Otiniano")
boxplot0 <- ggplot(data=Plot)+
  geom_boxplot(mapping = aes(x=Area))+
  ggtitle(label = "Boxplot de Areas de Lima", subtitle = "A.Otiniano")
histograma

boxplot0

library(cowplot)
plot_grid(boxplot0, histograma, nrow = 1, rel_widths = c(2.3, 1))

  • Aplicando a Mapas:
histograma2 <- ggplot(data=Provincias)+
  geom_histogram(mapping = aes(x=Area))+
  ggtitle(label = "Histograma Area")+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y = element_blank(),
        axis.ticks.y =element_blank(),
        axis.text.y=element_blank(),
        panel.background =element_blank() )

gg_inset_map1 <- ggdraw() +
  draw_plot(tt) +
  draw_plot(histograma2, x = 0.15, y = 0.32, width = 0.25, height = 0.3)
gg_inset_map1

Parte Final:

Extras:

¿Cómo obtener de un poligono información de puntos?

library(sf)
library(mapview)

head(breweries)
head(franconia)
puntos <- as(breweries, "Spatial")
lineas <-  as(franconia, "Spatial")

#convertimos a sf:
puntos <- st_as_sf(puntos)
lineas <- st_as_sf(lineas)

#intersectar poligonos con puntos, manteniendo amba informacion

union <- st_intersection(lineas, puntos)
colnames(puntos)
## [1] "brewery"               "address"               "zipcode"              
## [4] "village"               "state"                 "founded"              
## [7] "number.of.types"       "number.seasonal.beers" "geometry"
colnames(lineas)
## [1] "NUTS_ID"    "SHAPE_AREA" "SHAPE_LEN"  "CNTR_CODE"  "NAME_ASCI" 
## [6] "district"   "geometry"
colnames(union)
##  [1] "NUTS_ID"               "SHAPE_AREA"            "SHAPE_LEN"            
##  [4] "CNTR_CODE"             "NAME_ASCI"             "district"             
##  [7] "brewery"               "address"               "zipcode"              
## [10] "village"               "state"                 "founded"              
## [13] "number.of.types"       "number.seasonal.beers" "geometry"

Ahora lo plotearemos para que vean su utilidad:

Graficos como pop up:

Usaremos una data denominada meuse:

Mapa Final:

Mapa con Capas de Datos:

Puntos, Poligonos y DEM:

Falta!!!

my_data <- mtcars
library(rpivotTable)
## Warning: package 'rpivotTable' was built under R version 4.1.1
rpivotTable(as.data.frame(my_data))

Comentarios Finales:

Pronto explicaremos la potencialidad geoespacial de leaflet(), sf() y mapbox() unidos a plotly() y crosstalk() entre otros para generar mapas interactivos geoespaciales. Para el análisis multiscience que considero filtros dinámicos en mapas, gráficos, tabla y cálclos estaísticos y geoestadístico interactuando simultáneamente se necesitarán algunas herramientas más que pronto veremos :D!!!.